/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Sony
 */
public class CommonTableModel extends AbstractTableModel {

    private Vector colHeaders;
    private Vector tableData;

    public CommonTableModel() {
    }

    public CommonTableModel(ResultSet rsData) {
        try {
            ResultSetMetaData rsMeta = rsData.getMetaData(); // read metadata in ResultSet
            int count = rsMeta.getColumnCount(); // read number Field in ResultSet
            tableData = new Vector();
            colHeaders = new Vector(count);
            //Lap tuong ung voi so phan tu columnHeaders de lay ten cua tung cot trong bang
            for (int i = 1; i <= count; i++) {
                colHeaders.addElement(rsMeta.getColumnName(i));
            }
            //lap tu record dau tien den cuoi ResultSet de lay du lieu add vao table
            while (rsData.next()) {
                //Khai bao 1 doi tuong dataRow de chua du lieu doc tu table
                Vector dataRow = new Vector(count);
                //lap theo so cot cua bang de lay thong tin cua tung doi tuong bo vao dataRow
                for (int i = 1; i <= count; i++) {
                    dataRow.addElement(rsData.getObject(i));
                }

                tableData.addElement(dataRow);
            }

        } catch (SQLException ex) {
            Logger.getLogger(CommonTableModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public int getRowCount() {
        return tableData.size();
    }

    @Override
    public int getColumnCount() {
        return colHeaders.size();
    }

    @Override
    public String getColumnName(int column) {
        return (String) colHeaders.elementAt(column); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Object getValueAt(int row, int column) {

        Vector rowData = (Vector) tableData.elementAt(row);
        return rowData.elementAt(column);
    }
}
